package labilabyrinth.activity;

import java.util.Map.Entry;
import java.util.TreeMap;

import android.R;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class LevelChooserActivity extends ListActivity{
	
	private TreeMap<Integer, String> levelsSorted;
	public  String[] levels;
	private String currLevel;
	private ListView lv;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	  super.onCreate(savedInstanceState);
	  setTitle("Choose level");
	  levelsSorted = new TreeMap<Integer, String>();
	  //TODO loadLevels();
	  lv = getListView();
	  levels = fileList();
	  lv.setTextFilterEnabled(true);
	  lv.setOnItemClickListener(new OnItemClickListener() {
	    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
	      currLevel = ((TextView) view).getText().toString();
	      startGame(currLevel);
	    }
	  });
	  setListAdapter(new ArrayAdapter<String>(this,R.layout.simple_list_item_1,this.levels));
	}
	
	public void loadLevels(){
		try{
		 String[] files =  fileList();
		 for(int i=0;i<files.length;i++){
			 if(isValidLVL(files[i])){
				 String[] temp = files[i].split("_");
				 Integer in = Integer.parseInt(temp[0]);
				 String n = temp[1];
				 levelsSorted.put(in,n); 
			 } 
		 }
		 int i=0;
		 for(Entry<Integer, String> entry : levelsSorted.entrySet()){
			 this.levels =  new String[levelsSorted.size()];
			 this.levels[i] = Integer.toString(entry.getKey())+"_"+entry.getValue();
			 i++;
		 }
		}catch(Exception e){
			Log.d("lvl","getting lvl from internal storage error");
		}
	}
	
	private boolean isValidLVL(String lvl){
		return lvl.endsWith(".lvl");
	}
	
	public void startGame(String level){
		 Intent intent = new Intent(this, GameActivity.class);
		 intent.putExtra("level", currLevel);
		 startActivity(intent);
	}

}
